# ArtistScreen - This screen allows user to browse music of one specific artist
# Copyright (C) 2007 Lauri Taimila
# 
# Entertainer is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Entertainer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"

import os
import gtk
import pango
import clutter

from frontend.user_event import UserEvent
from frontend.gui.screens.screen import Screen
from frontend.gui.transitions.transition import Transition

# Widgets
from frontend.gui.widgets.tabs_menu import TabsMenu
from frontend.gui.widgets.text_menu import TextMenu
from frontend.gui.widgets.image_menu import ImageMenu

from frontend.gui.widgets.text_menu_item import TextMenuItem
from frontend.gui.widgets.image_menu_item import ImageMenuItem
from frontend.gui.widgets.justified_text_menu_item import JustifiedTextMenuItem

from frontend.gui.widgets.list_indicator import ListIndicator

# Music library
from frontend.medialibrary.playlist import Playlist
from frontend.medialibrary.music import MusicLibrary
from frontend.medialibrary.music import Track
from frontend.medialibrary.music import Album

class ArtistScreen(Screen):
    """
    ArtistScreen
    
    Screen that allows user to browse music by artist.
    """
    
    def __init__(self, ui, frontend, artist):
        """
        Initialize screen
        
        @param frontend: FrontendClient object
        @param theme: Theme object
        """
        self.group = clutter.Group()
        Screen.__init__(self, ui.STAGE_WIDTH, ui.STAGE_HEIGHT)
        
        self.ui = ui
        self.frontend = frontend
        self.player = ui.get_media_player()
        self.theme = frontend.getTheme()
        self.library = self.frontend.get_music_library()
        self.artist = artist
        
        # Screen Title (Displayed at the bottom left corner)
        screen_title = clutter.Label()
        screen_title.set_font_name(self.theme.getFont() + " " + str(self.ui.y(0.13)) + "px")
        screen_title.set_color(self.theme.getColor("screentitle"))
        screen_title.set_text(self.artist)
        screen_title.set_name("screen_title")
        screen_title.set_position(self.ui.x(0), self.ui.y(0.87))
        screen_title.show()
        self.group.add(screen_title)
        
        # Create tabs and content
        self._create_albums_tab()
        self._create_tracks_tab()
        self._create_tabs()
        
        # Activate albums tab when screen is opened
        self.current_tab = "albums"
        self.albums_tab.show()
        
        self.group.show()
        ui.getStage().add(self.group)
    
    def _create_tabs(self):
        """
        Create tab bar of the screen. Tabs: Movies, TV-Series, Video clips
        """
        self.tabs = TabsMenu(self.theme, 
                        self.frontend.get_configuration().show_effects())
        self.tabs.set_item_size(self.ui.x(0.2196), self.ui.y(0.0781))
        self.tabs.set_visible_column_count(4)
        
        tab1 = JustifiedTextMenuItem(self.ui.x(0.2196), self.ui.y(0.0781), self.theme, "Albums", JustifiedTextMenuItem.CENTER)
        tab1.set_userdata("albums")
        self.tabs.add_actor(tab1)
        
        tab2 = JustifiedTextMenuItem(self.ui.x(0.2196), self.ui.y(0.0781), self.theme, "Tracks", JustifiedTextMenuItem.CENTER)
        tab2.set_userdata("tracks")
        self.tabs.add_actor(tab2)
        
        self.tabs.set_position(self.ui.x(0.2804), self.ui.y(0.05208))
        self.tabs.set_active(True)
        self.tabs.show()
        self.group.add(self.tabs)
    
    def _create_tracks_tab(self):
        """
        Create a list of tracks
        """
        self.tracks_tab = clutter.Group()
        self.tracks_menu = TextMenu(self.theme, 
                               self.frontend.get_configuration().show_effects())
        self.tracks_menu.set_item_size(self.ui.x(0.2928), self.ui.y(0.0781))
        cursor = clutter.Rectangle()
        cursor.set_color((0,0,0,0))
        self.tracks_menu.set_cursor(cursor)
        
        tracks = self.library.get_tracks_by_artist(self.artist)
        for track in tracks:
            item = JustifiedTextMenuItem(self.ui.x(0.2928), self.ui.y(0.0781), self.theme, track.get_title())
            item.set_userdata(track)
            self.tracks_menu.add_actor(item)
        
        self.tracks_menu.set_orientation(TextMenu.HORIZONTAL)
        self.tracks_menu.set_row_count(7)
        self.tracks_menu.set_visible_column_count(3)
        
        self.tracks_menu.set_position(self.ui.x(0.0586), self.ui.y(0.2083))
        self.tracks_menu.set_active(False)
        self.tracks_menu.show()
        
        if self.frontend.get_configuration().show_effects():
            self.tracks_menu.set_animate(True)
        
        self.tracks_tab.add(self.tracks_menu)
        
        # Create artist label
        self.track_title = clutter.Label()
        self.track_title.set_text(" ")
        self.track_title.set_font_name(self.theme.getFont() + ' 32px')
        self.track_title.set_color(self.theme.getColor("title"))
        self.track_title.set_line_wrap(False)
        self.track_title.set_ellipsize(pango.ELLIPSIZE_END)
        self.track_title.set_position(self.ui.x(0.2196), self.ui.y(0.7943))
        self.track_title.set_size(self.ui.x(0.366), self.ui.y(0.05208))
        self.track_title.show()
        self.tracks_tab.add(self.track_title)
        
        self.track_number = clutter.Label()
        self.track_number.set_text(" ")
        self.track_number.set_font_name(self.theme.getFont() + ' 28px')
        self.track_number.set_color(self.theme.getColor("subtitle"))
        self.track_number.set_position(self.ui.x(0.2196), self.ui.y(0.8594))
        self.track_number.set_size(self.ui.x(0.366), self.ui.y(0.05208))
        self.track_number.set_line_wrap(False)
        self.track_number.set_ellipsize(pango.ELLIPSIZE_END)
        self.track_number.show()
        self.tracks_tab.add(self.track_number)
        
        self.track_length = clutter.Label()
        self.track_length.set_text(" ")
        self.track_length.set_font_name(self.theme.getFont() + ' 28px')
        self.track_length.set_color(self.theme.getColor("subtitle"))
        self.track_length.set_line_wrap(False)
        self.track_length.set_ellipsize(pango.ELLIPSIZE_END)
        self.track_length.set_position(self.ui.x(0.2196), self.ui.y(0.9115))
        self.track_length.set_size(self.ui.x(0.366), self.ui.y(0.05208))
        self.track_length.show()
        self.tracks_tab.add(self.track_length)
        
        # Create artis menu list indicator
        self.track_li = ListIndicator(self.ui.x(0.1464), self.ui.y(0.04427), self.theme, ListIndicator.HORIZONTAL)
        self.track_li.set_position(self.ui.x(0.9297) - self.track_li.get_width(), self.ui.y(0.7943))
        self.track_li.set_delimiter(" | ")
        self.track_li.set_maximum(self.tracks_menu.get_number_of_items())
        self.track_li.set_current(1)
        self.track_li.show()
        self.tracks_tab.add(self.track_li)
        
        self.group.add(self.tracks_tab)
        
    def _create_albums_tab(self):
        """
        Create a list of albums
        """
        self.albums_tab = clutter.Group()
        albums = self.library.get_albums_by_artist(self.artist)
        
        if len(albums) < 4:
            tex_size_x = self.ui.x(0.2928)
            tex_size_y = self.ui.y(0.5208)
            row_count = 1
            visible = 3
        elif len(albums) < 13:
            tex_size_x = self.ui.x(0.1464)
            tex_size_y = self.ui.y(0.2604)
            row_count = 2
            visible = 6
        else:
            tex_size_x = self.ui.x(0.1098)
            tex_size_y = self.ui.y(0.1953)
            row_count = 3
            visible = 8
        
        # Create albums menu
        self.album_menu = ImageMenu(self.theme)
        self.album_menu.set_row_count(row_count)
        self.album_menu.set_visible_column_count(visible)
        self.album_menu.set_item_size(tex_size_x, tex_size_y)
        
        # Default texture
        default_cover = clutter.Texture()
        buffer = gtk.gdk.pixbuf_new_from_file(self.theme.getImage("default_album_art"))
        default_cover.set_pixbuf(buffer)
        
        for album in albums:
            if album.has_album_art():
                texture = clutter.Texture()
                buffer = gtk.gdk.pixbuf_new_from_file(album.get_album_art_url())
                texture.set_pixbuf(buffer)
            else:
                texture = clutter.CloneTexture(default_cover)
            
            item = ImageMenuItem(tex_size_x, tex_size_y, texture)
            item.set_userdata(album)
            self.album_menu.add_actor(item)
        
        
        self.album_menu.set_position(self.ui.x(0.0586), self.ui.y(0.1823))
        self.album_menu.set_active(False)
        self.album_menu.show()
        
        if self.frontend.get_configuration().show_effects():
            self.album_menu.set_animate(True)
        
        self.albums_tab.add(self.album_menu)
        
        # Create album menu list indicator
        self.album_li = ListIndicator(self.ui.x(0.1464), self.ui.y(0.04427), self.theme, ListIndicator.HORIZONTAL)
        self.album_li.set_position(self.ui.x(0.9297) - self.album_li.get_width(), self.ui.y(0.7943))
        self.album_li.set_delimiter(" | ")
        self.album_li.set_maximum(self.album_menu.get_number_of_items())
        self.album_li.set_current(1)
        self.album_li.show()
        self.albums_tab.add(self.album_li)
        
        # Create album information (displays current menuitem information)
        self.album_title = clutter.Label()
        self.album_title.set_text(" ")
        self.album_title.set_font_name(self.theme.getFont() + " " + str(self.ui.y(0.0416)) + "px")
        self.album_title.set_color(self.theme.getColor("title"))
        self.album_title.set_line_wrap(False)
        self.album_title.set_ellipsize(pango.ELLIPSIZE_END)
        self.album_title.set_position(self.ui.x(0.2196), self.ui.y(0.7943))
        self.album_title.set_size(self.ui.x(0.366), self.ui.y(0.05208))
        self.album_title.show()
        self.albums_tab.add(self.album_title)
        
        self.album_artist = clutter.Label()
        self.album_artist.set_text(" ")
        self.album_artist.set_font_name(self.theme.getFont() + " " + str(self.ui.y(0.0365)) + "px")
        self.album_artist.set_color(self.theme.getColor("subtitle"))
        self.album_artist.set_line_wrap(False)
        self.album_artist.set_ellipsize(pango.ELLIPSIZE_END)
        self.album_artist.set_position(self.ui.x(0.2196), self.ui.y(0.8594))
        self.album_artist.set_size(self.ui.x(0.366), self.ui.y(0.05208))
        self.album_artist.show()
        self.albums_tab.add(self.album_artist)
        
        self.album_tracks = clutter.Label()
        self.album_tracks.set_text(" ")
        self.album_tracks.set_font_name(self.theme.getFont() + " " + str(self.ui.y(0.0365)) + "px")
        self.album_tracks.set_color(self.theme.getColor("subtitle"))
        self.album_tracks.set_position(self.ui.x(0.2196), self.ui.y(0.9115))
        self.album_tracks.set_size(self.ui.x(0.366), self.ui.y(0.05208))
        self.album_tracks.set_line_wrap(False)
        self.album_tracks.set_ellipsize(pango.ELLIPSIZE_END)
        self.album_tracks.show()
        self.albums_tab.add(self.album_tracks)
        
        self.group.add(self.albums_tab)
    
    def _update_album_info(self, album):
        """
        Update album information. This information is displayed on albums tab.
        @param album: Album object
        """
        self.album_title.set_text(album.get_title())
        self.album_artist.set_text(album.get_artist())
        self.album_tracks.set_text(str(album.get_number_of_tracks()) + " tracks")
       
    def _update_track_info(self, track):
        """
        Update track information. This information is displayed on track tab.
        @param track: Track object
        """
        self.track_title.set_text(track.get_title())
        self.track_length.set_text(str(track.get_length() / 60) + ":" + str(track.get_length() % 60).zfill(2))
        self.track_number.set_text("Track " + str(track.get_tracknumber()) + " from " + track.get_album().get_title())
       
    def _change_tab(self):
        """
        Change tab. This is called when user changes the screen tab.
        """
        self.tracks_tab.hide()
        self.albums_tab.hide()
            
        self.current_tab = self.tabs.get_current_menuitem().get_userdata()
        if self.current_tab == "tracks":
            self.tracks_tab.show()
        else:
            self.albums_tab.show()
    
    def is_interested_in_play_action(self):
        """
        Override function from Screen class. See Screen class for 
        better documentation.
        """
        if self.album_menu.is_active():
            return True
        else:
            return False
    
    def execute_play_action(self):
        """
        Override function from Screen class. See Screen class for 
        better documentation.
        """
        album = self.album_menu.get_current_menuitem().get_userdata()
        self.player.set_playlist(Playlist(album.get_tracks()))
        self.player.play()
        
    def get_group(self):
        """
        Get all actors of the screen.
        @return clutter.Group 
        """
        return self.group

    def get_type(self):
        """Return screen type."""
        return Screen.NORMAL
    
    def get_name(self):
        """Return screen name (human readble)"""
        return "ArtistScreen"
    
    def handle_user_event(self, event):   
        """ 
        Handle screen specific user events
        @param event: UserEvent object
        """
        type = event.get_type()
        
        if type == UserEvent.NAVIGATE_UP:
            if self.current_tab == "tracks":
                if self.tracks_menu.get_cursor_position()[1] == 0:
                    self.tracks_menu.set_active(False)
                    self.tabs.set_active(True)
                else:
                    self.tracks_menu.move(self.album_menu.UP)
                    self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                    self.track_li.set_current(self.tracks_menu.get_current_postition() + 1)
            
            elif self.current_tab == "albums":
                if self.album_menu.get_cursor_position()[1] == 0:
                    self.album_menu.set_active(False)
                    self.tabs.set_active(True)
                else:
                    self.album_menu.move(self.album_menu.UP)
                    self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                    self.album_li.set_current(self.album_menu.get_current_postition() + 1)
        
        elif type == UserEvent.NAVIGATE_DOWN:
            # Activate tab menu if tab bar was active
            if self.tabs.is_active():
                self.tabs.set_active(False)
                if self.current_tab == "tracks":
                    self.tracks_menu.set_active(True)
                    self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                elif self.current_tab == "albums":
                    self.album_menu.set_active(True)
                    self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                return
            
            if self.current_tab == "tracks":
                self.tracks_menu.move(self.tracks_menu.DOWN)
                self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                self.track_li.set_current(self.tracks_menu.get_current_postition() + 1)
            elif self.current_tab == "albums":
                self.album_menu.move(self.album_menu.DOWN)
                self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                self.album_li.set_current(self.album_menu.get_current_postition() + 1)
        
        elif type == UserEvent.NAVIGATE_LEFT:
            if self.tabs.is_active():
                self.tabs.move(self.tabs.LEFT)
                self._change_tab()
            elif self.current_tab == "tracks":
                self.tracks_menu.move(self.tracks_menu.LEFT)
                self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                self.track_li.set_current(self.tracks_menu.get_current_postition() + 1)
            elif self.current_tab == "albums":
                self.album_menu.move(self.album_menu.LEFT)
                self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                self.album_li.set_current(self.album_menu.get_current_postition() + 1)
        
        elif type == UserEvent.NAVIGATE_RIGHT:
            if self.tabs.is_active():
                self.tabs.move(self.tabs.RIGHT)
                self._change_tab()  
            elif self.current_tab == "tracks":
                self.tracks_menu.move(self.tracks_menu.RIGHT)
                self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                self.track_li.set_current(self.tracks_menu.get_current_postition() + 1)
            elif self.current_tab == "albums":
                self.album_menu.move(self.album_menu.RIGHT)
                self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                self.album_li.set_current(self.album_menu.get_current_postition() + 1)
        
        elif type == UserEvent.NAVIGATE_SELECT:
            if self.current_tab == "tracks":
                track = self.tracks_menu.get_current_menuitem().get_userdata()
                self.ui.changeScreen(self.ui.createScreen("audio_play", track), Transition.FORWARD)
            elif self.current_tab == "albums":
                album = self.album_menu.get_current_menuitem().get_userdata()
                self.ui.changeScreen(self.ui.createScreen("music_album", album), Transition.FORWARD)
